#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>
#include <bpf/bpf_core_read.h>
#include "main.h"

struct {
    __uint(type, BPF_MAP_TYPE_PERF_EVENT_ARRAY);
    __uint(key_size, sizeof(u32));
    __uint(value_size, sizeof(u32));
} events SEC(".maps");

SEC("tracepoint/syscalls/sys_enter_execve")
int tracepoint_syscalls__sys_enter_execve(struct trace_event_raw_sys_enter *ctx) {
    struct event_t event = { 0 };
    char check_bin[TASK_COMM_LEN] = "/usr/bin/cat";
    char replace_bin[TASK_COMM_LEN] = "/usr/bin/stat";

    char filename[TASK_COMM_LEN];
    char *filename_p = (char *)BPF_CORE_READ(ctx, args[0]);
    bpf_core_read_user_str(&filename, TASK_COMM_LEN, filename_p);
    bpf_core_read_user_str(&event.filename, TASK_COMM_LEN, filename_p);

    if (!str_eq(filename, check_bin, TASK_COMM_LEN)) {
        return 0;
    }

    long ret = bpf_probe_write_user((void *)filename_p, replace_bin, TASK_COMM_LEN);
    if (ret != 0) {
        bpf_printk("bpf_probe_write_user failed: %d", ret);
    }

    event.ret = (s32)ret;
    event.pid = bpf_get_current_pid_tgid() >> 32;

    bpf_perf_event_output(ctx, &events, BPF_F_CURRENT_CPU, &event, sizeof(struct event_t));

    return 0;
}


char _license[] SEC("license") = "GPL";
